package biz

import (
	"github.com/yeahyf/go_base/crypto"
	"github.com/yeahyf/go_base/ept"
	"github.com/yeahyf/go_base/immut"
	"github.com/yeahyf/go_base/log"
	"jian-picture-service/model"
	"jian-picture-service/utils"
	"net/http"
	"strings"
)

func (req *UserAddReq) UserAdd() error {
	sysUser := &model.SysUser{
		Account:  req.User.Account,
		Address:  req.User.Address,
		Age:      req.User.Age,
		Desc:     req.User.Desc,
		Name:     req.User.Name,
		Password: crypto.MD5S(req.User.Password),
	}
	err := model.PictureDB.Debug().Create(sysUser).Error
	if err != nil {
		if strings.Contains(err.Error(), "for key 'sys_users.idx_account'") {
			return ept.New(UserExistsErrCode, "用户账号已存在")
		} else {
			return ept.NewWrapper(immut.CodeExRDSInsert, err)
		}
	}
	return nil
}

func (req *UserListReq) UserList() (*UserListResp, error) {
	var sysUsers []*model.SysUser
	var totalPage int64
	err := model.PictureDB.Debug().Where(&model.SysUser{Name: req.Keyword, Account: req.Keyword}).
		Find(&sysUsers).
		Count(&totalPage).
		Limit(int(req.PageInfo.PageSize)).
		Offset(int(req.PageInfo.PageSize * req.PageInfo.PageNumber)).Error
	if err != nil {
		log.Error(err)
		return nil, err
	}

	res := &UserListResp{
		PageInfo: &PageInfo{
			TotalPage:  int32(totalPage),
			PageSize:   req.PageInfo.PageSize,
			PageNumber: req.PageInfo.PageNumber,
		},
	}

	for _, user := range sysUsers {
		res.UserList = append(res.UserList, getUserBySysUser(user))
	}
	return res, nil
}

func (req *UserLoginReq) UserLogin() (*UserLoginResp, error) {
	su := &model.SysUser{}
	result := model.PictureDB.Debug().Where(&model.SysUser{Account: req.Account, Password: crypto.MD5S(req.Password)}).Find(su)
	if err := result.Error; err != nil {
		log.Error(err)
		return nil, ept.NewWrapper(immut.CodeExRDSSelect, err)
	}
	if result.RowsAffected == 0 {
		// 未找到用户
		return nil, ept.New(http.StatusUnauthorized, "用户名或密码错误")
	}
	return &UserLoginResp{
		Token: utils.GetToken(su.ID, su.Name),
		User:  getUserBySysUser(su),
	}, nil
}

func (req *UserUpdateReq) UserUpdate() error {
	su := &model.SysUser{}

	up := map[string]any{
		"address": req.User.Address,
		"age":     req.User.Age,
		"desc":    req.User.Desc,
		"name":    req.User.Name,
		"avatar":  req.User.Avatar,
	}
	if req.User.Password != immut.Blank {
		up["password"] = crypto.MD5S(req.User.Password)
	}

	result := model.PictureDB.Debug().Where("account", su.Account).Updates(up)
	if result.RowsAffected == 0 {
		return ept.New(UserNotExistsErrCode, "修改失败,用户不存在")
	}
	if err := result.Error; err != nil {
		log.Error(err)
		return ept.NewWrapper(immut.CodeExRDSUpdate, err)
	}
	return nil
}

func (req *UserDelReq) UserDel() error {
	result := model.PictureDB.Debug().Where("account", req.Account).Delete(&model.SysUser{})
	if result.RowsAffected == 0 {
		return ept.New(UserNotExistsErrCode, "删除失败,用户不存在")
	}
	if err := result.Error; err != nil {
		log.Error(err)
		return ept.NewWrapper(immut.CodeExRDSDelete, err)
	}
	return nil
}

func (req *UserLoginReq) LoginInfo(id string) (*User, error) {
	su := &model.SysUser{}
	result := model.PictureDB.Debug().Where("id", id).Find(&su)
	if result.RowsAffected == 0 {
		// 这次不存在 需要让用户退出登录 返回401 账号已经不在了
		return nil, ept.New(http.StatusUnauthorized, "用户不存在")
	}
	if err := result.Error; err != nil {
		log.Error(err)
		return nil, ept.NewWrapper(immut.CodeExRDSSelect, err)
	}

	return getUserBySysUser(su), nil
}

func getUserBySysUser(su *model.SysUser) *User {
	return &User{
		Account: su.Account,
		Address: su.Address,
		Age:     su.Age,
		Desc:    su.Desc,
		Name:    su.Name,
		Avatar:  su.Avatar,
	}
}
